package com.peg.rules;

import com.peg.dataobjects.*;
import com.peg.dataobjects.ParsingError;

/**
 * @author sad
 */
//checked sequence tries to
public class Checkpoint extends ContainerRule {

    public Checkpoint(Rule rule) {
        setRule(rule);
    }

    @Override
    public boolean execute(Context context) {
        boolean result=false;
        int startIndex=context.getCurrentStreamIndex();
        int lastGoodStartIndex=context.getCurrentStreamIndex();
        while(result==false){
            lastGoodStartIndex=context.getCurrentStreamIndex();
            result = executeRule(getRule(), context);
            if(result==false){
                char c=context.getNextChar();
                if(c==0){
                    return false;
                }
            }else{
                break;
            }
        }
        if(lastGoodStartIndex!=startIndex){
            ParsingError error=new ParsingError();
            error.setStartOffset(startIndex);
            error.setLength(lastGoodStartIndex-startIndex);
            context.addError(error);
        }

        return result;
    }

    @Override
    public String toString() {
        return "Sequence";
    }
}